import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  HomeLeft, HomeWrapper, HomeRight, BackToTop,
} from './style';
import Topic from './components/Topic';
import List from './components/List';
import Recommend from './components/Recommend';
import Writer from './components/Writer';
import * as actionCreators from './store/actionCreators';

const Home = () => {
  const dispatch = useDispatch();
  const showScroll = useSelector((state: any) => state.getIn(['home', 'showScroll']));
  const handleBackToTop = () => {
    window.scrollTo(0, 0);
  };
  const handleScrollEvent = () => {
    if (document.documentElement.scrollTop >= document.body.clientHeight) {
      dispatch(actionCreators.toggleShowBackTop(true));
    } else {
      dispatch(actionCreators.toggleShowBackTop(false));
    }
  };
  useEffect(() => {
    window.addEventListener('scroll', handleScrollEvent);
    return () => {
      window.removeEventListener('scroll', handleScrollEvent);
    };
  }, []);
  return (
    <>
      <HomeWrapper>
        <HomeLeft>
          <Topic />
          <List />
        </HomeLeft>
        <HomeRight>
          <Recommend />
          <Writer />
        </HomeRight>
      </HomeWrapper>
      {
        showScroll
          ? <BackToTop onClick={handleBackToTop}>BackTop</BackToTop>
          : null
      }
    </>
  );
};

export default Home;
